#pragma once

#include <iostream>
#include <string>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include <cstring>

class Udpserver
{
public:
    Udpserver(int fd, std::string&ip,uint16_t port)
        : _socketfd(fd),
        _ip(ip),
        _port(port)

    {
    }
    // 创建
    void Init()
    {
        _socketfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_socketfd < 0)
        {
            perror("socket fail\n");
            exit(1);
        }
        std::cout << "socket success" << std::endl;
        struct sockaddr_in local;
        std::memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = inet_addr(_ip.c_str());
        // 绑定
        int n = bind(_socketfd, (sockaddr *)&local, sizeof(local));
        if (n != 0)
        {
            perror("bind fail\n");
        }
        std::cout << "bind success\n"
                  << std::endl;
    }
    void Start()
    {
        while (1)
        {
            // 我是服务器，我的接收到别人发过来的信息
            char buffer[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t s = recvfrom(_socketfd, buffer, sizeof(buffer) - 1, 0, (sockaddr *)&peer, &len);
            if (s > 0)
            {
                buffer[s] = 0;
                // 这个时候要去发送了。
                std::cout<<buffer<<std::endl;
                std::string echo_string = "client say@ ";
                echo_string += buffer;
                // 发送
                sendto(_socketfd, echo_string.c_str(), echo_string.size(), 0, (sockaddr *)&peer, len);
            }
        }
    }
    ~Udpserver() {}

private:
    int _socketfd; // 打开的网络文件
    // ip
    uint16_t _port;
    std::string _ip; // 点分十进制

    // 端口号
};